package com.lagou.homework.test01;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Test01 {

    public static void main(String[] args) {

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;

        try {

            // 1. 获取连接
            conn = JDBCUtils.getConnection();

            //2. 准备SQL, 使用问号占位符
            String sql = "select * from employee where name like ?";
            //3. 获取预处理对象
            ps = conn.prepareStatement(sql);
            // 设置占位符的数据
            ps.setString(1,"%张%");

            //执行查询
            resultSet = ps.executeQuery();
            System.out.println("使用like查询, 查询姓名中带'张'的成员有:");
            //遍历结果集
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                System.out.println("id:" + id + ", name:" + name);
        }

            System.out.println("------------------------");

            // 准备SQL语句, 获取预处理对象
            sql = "select * from employee where gender = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, "女");
            resultSet = ps.executeQuery();

            //执行查询并打印结果集
            System.out.println("性别为女的成员有:");
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                double salary = resultSet.getDouble("salary");
                System.out.println("id:" + id + ", name:" + name + ", salary:" + salary);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭数据库连接并释放相关资源
                JDBCUtils.close(conn, ps, resultSet);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
